<?php

declare(strict_types=1);

namespace App\Model;

use Aether\AetherModel;
use Carbon\Carbon;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Relations\BelongsTo;

/**
 * 教师模型.
 * @property int $id
 * @property string $name 教师姓名
 * @property int $age 年龄
 * @property int $gender 性别：1-男，2-女
 * @property string $avatar 头像URL
 * @property string $title 职称
 * @property string $major_subject 主讲科目
 * @property string $teaching_style 授课风格
 * @property string $introduction 教师简介
 * @property int $campus_id 所属校区ID
 * @property int $status 状态：0-禁用，1-启用
 * @property int $sort 排序
 * @property Carbon $created_at
 * @property Carbon $updated_at
 * @property Carbon $deleted_at
 */
class Teacher extends AetherModel
{
    protected ?string $table = 'da_teacher';

    protected array $fillable = [
        'name',
        'age',
        'gender',
        'avatar',
        'title',
        'major_subject',
        'teaching_style',
        'introduction',
        'campus_id',
        'status',
        'sort',
    ];

    protected array $casts = [
        'id' => 'integer',
        'age' => 'integer',
        'gender' => 'integer',
        'campus_id' => 'integer',
        'status' => 'integer',
        'sort' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    protected array|bool|string $sortable = 'sort';

    protected array $search = [
        'name' => 'like',
        'campus_id' => '=',
    ];

    /**
     * 所属校区.
     */
    public function campus(): BelongsTo
    {
        return $this->belongsTo(Campus::class, 'campus_id', 'id')
            ->where('status', 1)
            ->whereNull('deleted_at');
    }

    /**
     * 按校区查询.
     */
    public function scopeCampusId(Builder $query, int $campusId): Builder
    {
        return $query->where('campus_id', $campusId);
    }

    /**
     * 按科目查询.
     */
    public function scopeSubject(Builder $query, string $subject): Builder
    {
        return $query->where('major_subject', 'like', "%{$subject}%");
    }

    /**
     * 搜索教师.
     */
    public function scopeSearch(Builder $query, string $keyword): Builder
    {
        return $query->where(function ($q) use ($keyword) {
            $q->where('name', 'like', "%{$keyword}%")
                ->orWhere('title', 'like', "%{$keyword}%")
                ->orWhere('major_subject', 'like', "%{$keyword}%")
                ->orWhere('introduction', 'like', "%{$keyword}%");
        });
    }

    /**
     * 查询启用的教师.
     */
    public function scopeEnabled(Builder $query): Builder
    {
        return $query->where('status', 1);
    }
}
